package com.penghaisoft.microwms.product.web.controller.insidewarehouse;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;

import lombok.extern.slf4j.Slf4j;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.base.model.BaseDictionary;
import com.penghaisoft.microwms.common.controller.BaseController;
import com.penghaisoft.microwms.common.dto.ConProCondDto;
import com.penghaisoft.microwms.common.dto.ProStorageDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.dto.UserFactoryDto;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.IMesInterfaceService;
import com.penghaisoft.microwms.common.service.MesProperties;
import com.penghaisoft.microwms.common.util.ExcelExpUtil;
import com.penghaisoft.microwms.common.wms.model.MesConProRequired;
import com.penghaisoft.microwms.common.wms.model.ProStorageSn;
import com.penghaisoft.microwms.common.wms.model.RawLockLog;
import com.penghaisoft.microwms.common.wms.model.RawStorageSn;
import com.penghaisoft.microwms.product.service.IBaseDictionaryService;
import com.penghaisoft.microwms.product.service.IProStorageSnService;

/**
 * @Description 成品库内管理相关Controller
 * @author luoteng
 * @date 2018年6月6日 下午3:02:17 
 * @version 1.0
 */
@RestController
@RequestMapping(value = "/insidewarehouse")
@Slf4j
public class InsideWarehouseController extends BaseController {

	@Autowired
	private IProStorageSnService proStorageSnService;
    @Autowired
	private IMesInterfaceService mesInterfaceService;
	@Resource
	private MesProperties mesProperties;
	@Autowired
	private IBaseDictionaryService baseDictionaryService;
    
	/**
	 * @Title storagesnList
	 * @Description 成品库存明细查询
	 * @param page
	 * @param rows
	 * @param proStorageSn
	 * @return
	 */
	@PostMapping("storagesn/list")
	public TransResult storagesnList(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows, ProStorageSn proStorageSn) {
		proStorageSn.preQuery();
		Pager<ProStorageSn> result = proStorageSnService.findListByCondition(page, rows, proStorageSn);
		
		String sumInfo = result.getOrder();
		if (sumInfo != null && sumInfo.length() > 0) {
			result.setOrder(sumInfo);
		}
		
		return success(result);
	}
	
	/**
	 * @Title: changeList
	 * @Description: 查询成品库存变更历史
	 * @date 2019年3月15日 上午11:22:59
	 * @author luoteng
	 * @param page
	 * @param rows
	 * @param proStorageSn
	 * @return TransResult   
	 */
	@PostMapping("storage/change/list")
	public TransResult changeList(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows, ProStorageSn proStorageSn) {
		proStorageSn.preQuery();
		Pager<ProStorageSn> result = proStorageSnService.queryStorageChangeList(page, rows, proStorageSn);
		
		
		
		return success(result);
	}
	/**
	 * @Title: changeList
	 * @Description: 查询成品库存变更历史导出
	 * @date 2019年3月15日 上午11:22:59
	 * @author luoteng
	 * @param page
	 * @param rows
	 * @param proStorageSn
	 * @return TransResult   
	 */
	@GetMapping("storage/change/list/exp")
	public String changeListExp(ProStorageSn proStorageSn, HttpServletRequest request, HttpServletResponse response){
		
		proStorageSn.preQuery();
		int page = 1;
		int rows = 60000;
		Pager<ProStorageSn> result = proStorageSnService.queryStorageChangeList(page, rows, proStorageSn);
		List<ProStorageSn> dataList = result.getRecords();
		

		List<Map> columnList = new ArrayList<Map>();
		Map<String,String> columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "合同编号");
		columnMap.put("columnBeanName", "contractNo");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号");
		columnMap.put("columnBeanName", "model");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号描述");
		columnMap.put("columnBeanName", "modelDesc");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号类型");
		columnMap.put("columnBeanName", "modelType");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "期初数量");
		columnMap.put("columnBeanName", "storageSAmount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "入库数量");
		columnMap.put("columnBeanName", "inAmount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "出库数量");
		columnMap.put("columnBeanName", "outAmount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "借入数量");
		columnMap.put("columnBeanName", "changeInNum");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "借出数量");
		columnMap.put("columnBeanName", "changeOutNum");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "期末数量");
		columnMap.put("columnBeanName", "storageEAmount");
		columnList.add(columnMap);
		
		SXSSFWorkbook sw = ExcelExpUtil.generateWorkbook(dataList, columnList);
		
		OutputStream out = null;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String sdfDate = sdf.format(date);
		String fileName = "成品库存变更历史"+sdfDate+".xlsx";// 文件名
		try {
			out = response.getOutputStream();
			response.setContentType("application/force-download");// 设置强制下载不打开
			response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
			sw.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
		return "sucess";
		
	}
	
	
	
	
	/** 
	* @Title: storagesnkulingList 
	* @Description: 成品库龄超期
	* @param @param page
	* @param @param rows
	* @param @param proStorageSn
	* @param @return  参数说明 
	* @return TransResult    返回类型
	* @author jzh 
	* @throws 
	*/
	@PostMapping("storagesn/kulingList")
	public TransResult storagesnkulingList(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows, ProStorageSn proStorageSn) {
		proStorageSn.preQuery();
		
//		proStorageSn.setKulingConstant(Constant.KULING_OFF);
		
		List<UserFactoryDto> fcList = getUserFactories();
		if(fcList != null && !fcList.isEmpty() && fcList.get(0).getWarningDays() != null) {
			proStorageSn.setKulingConstant(new BigDecimal(fcList.get(0).getWarningDays()));
		}else {
			TransResult result = new TransResult();
			result.setCode(Constant.FAIL);
			result.setMsg("请联系管理员，配置预警天数！");
			return result;
		}
		Pager<ProStorageSn> result = proStorageSnService.findKulingList(page, rows, proStorageSn);
		return success(result);
	}
	/**
	 * @Title storagesnList
	 * @Description 成品库存查询
	 * @param page
	 * @param rows
	 * @param proStorageDto
	 * @return
	 */
	@PostMapping("storage/list")
	public TransResult storageList(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows, ProStorageDto proStorageDto) {

		Pager<ProStorageDto> result = proStorageSnService.findStorageListByCondition(page, rows, proStorageDto);
		
		String sumInfo = result.getOrder();
		if (sumInfo != null && sumInfo.length() > 0) {
			result.setOrder(sumInfo);
		}
		
		return success(result);
	}
	
	/**
	 * @Title: storageListHZ
	 * @Description: 成品库存汇总查询
	 * @date 2019年1月28日 下午3:18:04
	 * @param page
	 * @param rows
	 * @param proStorageDto
	 * @return TransResult   
	 */
	@PostMapping("storage/list/hz")
	public TransResult storageListHZ(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows, ProStorageDto proStorageDto) {

		Pager<ProStorageDto> result = proStorageSnService.findStorageListByConditionHZ(page, rows, proStorageDto);
		
		String sumInfo = result.getOrder();
		if (sumInfo != null && sumInfo.length() > 0) {
			result.setOrder(sumInfo);
		}
		
		return success(result);
	}

	/** 
	* @Title: listExp 
	* @Description: 成品库存导出
	* @param @param proStorageDto
	* @param @param request
	* @param @param response
	* @param @return  参数说明 
	* @return String    返回类型
	* @author jzh 
	* @throws 
	*/
	@GetMapping("proStorage/listExp")
	public String listExp(ProStorageDto proStorageDto, HttpServletRequest request, HttpServletResponse response){
		
		List<ProStorageDto> dataList = proStorageSnService.findStorageListExp(proStorageDto);
		
		BaseDictionary baseDictionary1 = new BaseDictionary();
		baseDictionary1.setActiveFlag("1");
		baseDictionary1.setDicType("model_type_p");
		List<BaseDictionary> list1 = baseDictionaryService.queryAllByCondition(baseDictionary1);
		if (dataList != null && !dataList.isEmpty()) {
			for (ProStorageDto tmpData : dataList) {
				if (list1 != null && !list1.isEmpty()) {
					for (BaseDictionary tmp : list1) {
						// 判断型号类型
						if (tmp.getDicCode().equals(tmpData.getModelType())) {
							tmpData.setModelType(tmp.getDicName());
						}
						// 判断产品类型
						if ("0".equals(tmpData.getType())) {
							tmpData.setType("正品");
						}
						if ("1".equals(tmpData.getType())) {
							tmpData.setType("样品");
						}
						
					}
				}
			}
		}
		
		List<Map> columnList = new ArrayList<Map>();
		Map<String,String> columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "合同号");
		columnMap.put("columnBeanName", "contractNo");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号");
		columnMap.put("columnBeanName", "model");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号描述");
		columnMap.put("columnBeanName", "modelDesc");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号类型");
		columnMap.put("columnBeanName", "modelType");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "产品类型");
		columnMap.put("columnBeanName", "type");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "个数");
		columnMap.put("columnBeanName", "amount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "单位");
		columnMap.put("columnBeanName", "unit");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "库存数量 ");
		columnMap.put("columnBeanName", "iventAmount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "可用数量 ");
		columnMap.put("columnBeanName", "availAmount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "冻结数量");
		columnMap.put("columnBeanName", "lockAmount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "库位 ");
		columnMap.put("columnBeanName", "wlCode");
		columnList.add(columnMap);
		
		SXSSFWorkbook sw = ExcelExpUtil.generateWorkbook(dataList, columnList);
		
		OutputStream out = null;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String sdfDate = sdf.format(date);
		String fileName = "成品库存查询"+sdfDate+".xlsx";// 文件名
		try {
			out = response.getOutputStream();
			response.setContentType("application/force-download");// 设置强制下载不打开
			response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
			sw.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	//	//记录导出日志
	//	BaseUserExportLog exportLog = new BaseUserExportLog();
	//	exportLog.setTableName("OdsProKcfp");
	//	String expCond = JSON.toJSONString(odsProKcfp);
	//	exportLog.setExpcondition(expCond);
	//	if (dataList!=null) {
	//		exportLog.setExportNum(dataList.size());
	//	}else {
	//		exportLog.setExportNum(0);
	//	}
	//	exportLog.setUserDefined1("excel");
	//	exportLog.setUserDefined2("库存分配查询");
	//	exportLog.setFactoryCode(getCurrentFactoryCode());
	//	exportLog.setCreateBy(getLoginName());
	//	userService.addExportLog(exportLog);
		
		return "sucess";
	}
	
	@GetMapping("proStorage/listExp/hz")
	public String listExpHz(ProStorageDto proStorageDto, HttpServletRequest request, HttpServletResponse response){
		
		List<ProStorageDto> dataList = proStorageSnService.findStorageListExpHZ(proStorageDto);
		
		BaseDictionary baseDictionary1 = new BaseDictionary();
		baseDictionary1.setActiveFlag("1");
		baseDictionary1.setDicType("model_type_p");
		List<BaseDictionary> list1 = baseDictionaryService.queryAllByCondition(baseDictionary1);
		if (dataList != null && !dataList.isEmpty()) {
			for (ProStorageDto tmpData : dataList) {
				if (list1 != null && !list1.isEmpty()) {
					for (BaseDictionary tmp : list1) {
						// 判断型号类型
						if (tmp.getDicCode().equals(tmpData.getModelType())) {
							tmpData.setModelType(tmp.getDicName());
						}
						// 判断产品类型
						if ("0".equals(tmpData.getType())) {
							tmpData.setType("正品");
						}
						if ("1".equals(tmpData.getType())) {
							tmpData.setType("样品");
						}
						
					}
				}
			}
		}
		
		List<Map> columnList = new ArrayList<Map>();
		Map<String,String> columnMap = new HashMap<String,String>();
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号");
		columnMap.put("columnBeanName", "model");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号描述");
		columnMap.put("columnBeanName", "modelDesc");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号类型");
		columnMap.put("columnBeanName", "modelType");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "个数");
		columnMap.put("columnBeanName", "amount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "单位");
		columnMap.put("columnBeanName", "unit");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "库存数量 ");
		columnMap.put("columnBeanName", "iventAmount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "可用数量 ");
		columnMap.put("columnBeanName", "availAmount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "冻结数量");
		columnMap.put("columnBeanName", "lockAmount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "库位 ");
		columnMap.put("columnBeanName", "wlCode");
		columnList.add(columnMap);
		
		SXSSFWorkbook sw = ExcelExpUtil.generateWorkbook(dataList, columnList);
		
		OutputStream out = null;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String sdfDate = sdf.format(date);
		String fileName = "成品库存汇总查询"+sdfDate+".xlsx";// 文件名
		try {
			out = response.getOutputStream();
			response.setContentType("application/force-download");// 设置强制下载不打开
			response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
			sw.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	//	//记录导出日志
	//	BaseUserExportLog exportLog = new BaseUserExportLog();
	//	exportLog.setTableName("OdsProKcfp");
	//	String expCond = JSON.toJSONString(odsProKcfp);
	//	exportLog.setExpcondition(expCond);
	//	if (dataList!=null) {
	//		exportLog.setExportNum(dataList.size());
	//	}else {
	//		exportLog.setExportNum(0);
	//	}
	//	exportLog.setUserDefined1("excel");
	//	exportLog.setUserDefined2("库存分配查询");
	//	exportLog.setFactoryCode(getCurrentFactoryCode());
	//	exportLog.setCreateBy(getLoginName());
	//	userService.addExportLog(exportLog);
		
		return "sucess";
	}
	
	/** 
	* @Title: listSnExp 
	* @Description:成品明细导出
	* @param @param proStorageSn
	* @param @param request
	* @param @param response
	* @param @return  参数说明 
	* @return String    返回类型
	* @author jzh 
	* @throws 
	*/
	@GetMapping("proStorageSn/listSnExp")
	public String listSnExp(ProStorageSn proStorageSn, HttpServletRequest request, HttpServletResponse response){
		
		proStorageSn.setActiveFlag("1");
		List<ProStorageSn> dataList = proStorageSnService.findStorageSnListExp(proStorageSn);
		
		BaseDictionary baseDictionary1 = new BaseDictionary();
		baseDictionary1.setActiveFlag("1");
		baseDictionary1.setDicType("model_type_p");
		List<BaseDictionary> list1 = baseDictionaryService.queryAllByCondition(baseDictionary1);
		if (dataList != null && !dataList.isEmpty()) {
			for (ProStorageSn tmpData : dataList) {
				if (list1 != null && !list1.isEmpty()) {
					for (BaseDictionary tmp : list1) {
						// 判断型号类型
						if (tmp.getDicCode().equals(tmpData.getModelType())) {
							tmpData.setModelType(tmp.getDicName());
						}
						// 判断产品类型
						if ("0".equals(tmpData.getType())) {
							tmpData.setType("正品");
						}
						else if ("1".equals(tmpData.getType())) {
							tmpData.setType("样品");
						}
						// 判断状态
						if ("0".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("可用");
						}
						else if ("1".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("冻结");
						}
						else if ("2".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("已出库");
						}
						else if ("3".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("报废");
						}
						// 判断冻结原因
						if ("2".equals(tmpData.getLockReason())){
							tmpData.setLockReason("质量冻结");
						}
						else if ("4".equals(tmpData.getLockReason())){
							tmpData.setLockReason("手工冻结");
						}
						
					}
				}
			}
		}
		
		List<Map> columnList = new ArrayList<Map>();
		Map<String,String> columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "合同编号");
		columnMap.put("columnBeanName", "contractNo");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "条码");
		columnMap.put("columnBeanName", "barcode");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号");
		columnMap.put("columnBeanName", "model");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号描述");
		columnMap.put("columnBeanName", "modelDesc");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号类型");
		columnMap.put("columnBeanName", "modelType");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "产品类型");
		columnMap.put("columnBeanName", "type");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "单位");
		columnMap.put("columnBeanName", "unit");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "数量");
		columnMap.put("columnBeanName", "amount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "状态");
		columnMap.put("columnBeanName", "barcodeStatus");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "库龄");
		columnMap.put("columnBeanName", "kuling");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "生产时间");
		columnMap.put("columnBeanName", "proManuDate");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "库位");
		columnMap.put("columnBeanName", "wlCode");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "冻结原因");
		columnMap.put("columnBeanName", "lockReason");
		columnList.add(columnMap);
		
		SXSSFWorkbook sw = ExcelExpUtil.generateWorkbook(dataList, columnList);
		
		OutputStream out = null;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String sdfDate = sdf.format(date);
		String fileName = "成品库存明细"+sdfDate+".xlsx";// 文件名
		try {
			out = response.getOutputStream();
			response.setContentType("application/force-download");// 设置强制下载不打开
			response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
			sw.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "sucess";
	}
	
	/**
	 * @wzhg 18619
	 * @param id
	 * @return
	 */
	@GetMapping("findById/{id}")
	public TransResult findById(@PathVariable("id")String id){
		ProStorageSn proStorageSn = new ProStorageSn();
		if(id != null && !"".equals(id)){
			proStorageSn = proStorageSnService.findById(id);
		}
		return success(proStorageSn);
	}
	
	@GetMapping("findById/new/{id}")
	public TransResult findByIdNew(@PathVariable("id")String id){
		ProStorageSn proStorageSn = new ProStorageSn();
		if(id != null && !"".equals(id)){
			proStorageSn = proStorageSnService.findById(id);
			if(proStorageSn != null && proStorageSn.getBarcodeStatus() != null) {
				TransResult result = new TransResult();
				if(proStorageSn.getBarcodeStatus().equals("2")) {
					result.setCode(Constant.FAIL);
					result.setMsg("该条码已经出库，不能修改合同号！");
					return result;
				}else if(proStorageSn.getBarcodeStatus().equals("1")) {
					result.setCode(Constant.FAIL);
					result.setMsg("该条码已经冻结，不能修改合同号！");
					return result;
				}else if(proStorageSn.getBarcodeStatus().equals("3")) {
					result.setCode(Constant.FAIL);
					result.setMsg("该条码已经抽检冻结，不能修改合同号！");
					return result;
				}
			}
		}
		return success(proStorageSn);
	}
	
	/** 
	* @Title: findByIdAbs 
	* @Description: 记账出库修改，数量取正值 
	* @param @param id
	* @param @return  参数说明 
	* @return TransResult    返回类型
	* @author jzh 
	* @throws 
	*/
	@GetMapping("findByIdAbs/{id}")
	public TransResult findByIdAbs(@PathVariable("id")String id){
		ProStorageSn proStorageSn = new ProStorageSn();
		if(id != null && !"".equals(id)){
			proStorageSn = proStorageSnService.findById(id);
			BigDecimal absAmount =  proStorageSn.getAmount().abs();
			proStorageSn.setAmount(absAmount);
		}
		return success(proStorageSn);
	}

	/**
	 * 根据id修改合同号(可以置为空可以修改为其他值)
	 * @wzhg 1865
	 * @param rawStorageSn
	 * @return
	 */
	@PostMapping("updateById")
	public TransResult updateById(RawStorageSn rawStorageSn , ProStorageSn proStorageSn){
		Date now = new Date();
		proStorageSn.setLastModifiedBy(getLoginName());
		proStorageSn.setGmtModified(now);
		proStorageSnService.update(proStorageSn);
		return success();
	}
	@GetMapping("storagesn/r/detail")
	public TransResult findRawStorageSnByCode(ProStorageSn proStorageSn) {
		proStorageSn.preQuery();
		List<ProStorageSn> list = proStorageSnService.findProStorageSnByCondition(proStorageSn);
		return success(list);
	}
	/**
	 * 成品冻结解冻
	 * @param list
	 * @return
	 */
	@PostMapping("storagesn/lockAndunlock")
	public TransResult updateList(@RequestBody List<ProStorageSn> list) {
		TransResult reuslt = new TransResult();
		String currentUserName = getLoginName();
		RawLockLog rawLockLog = new RawLockLog();
		rawLockLog.setLockBy(currentUserName);
		Resp resp = new Resp();
		try {
		 resp = proStorageSnService.updateProStorageSnStatus(list,rawLockLog);
		} catch(RuntimeException e){
			reuslt.setCode("0");
			System.out.print(e.getMessage());
			reuslt.setMsg(e.getMessage());
			return reuslt;
		}
		return fromResp(resp);
	}
	
	/** 
	* @Title: editProStorageSnIn 
	* @Description: 成品入库明细新增，修改
	* @param @param proStorageSn
	* @param @return  参数说明 
	* @return TransResult    返回类型
	* @author jzh 
	* @throws 
	*/
	@PostMapping("prosnin/edit")
	public TransResult editProStorageSnIn(ProStorageSn proStorageSn) {
		Date now = new Date();
		if(proStorageSn.getStorageSnId() == null || "".equals(proStorageSn.getStorageSnId())){
			proStorageSn.setActiveFlag("1");
			proStorageSn.setBarcodeStatus("0");
			proStorageSn.setCreateBy(getLoginName());
			proStorageSn.setGmtCreate(now);
			proStorageSnService.create(proStorageSn);
		}else{
			proStorageSn.setLastModifiedBy(getLoginName());
			proStorageSn.setGmtModified(now);
			proStorageSnService.update(proStorageSn);
		}
		return success();
	}
	
	/** 
	* @Title: deleteProStorageSn 
	* @Description: 成品入库明细删除
	* @param @param proStorageSn
	* @param @return  参数说明 
	* @return TransResult    返回类型
	* @author jzh 
	* @throws 
	*/
	@PostMapping("delectprosn")
	public TransResult deleteProStorageSn(ProStorageSn proStorageSn) {
		Date now = new Date();
//		有效标志 1-有效 0-无效
		proStorageSn.setActiveFlag("0");
		proStorageSn.setLastModifiedBy(getLoginName());
		proStorageSn.setGmtModified(now);
		proStorageSnService.update(proStorageSn);
		return success();
	}
	

	/** 
	* @Title: chargeListOut 
	* @Description: 记账出库明细查询
	* @param @param page
	* @param @param rows
	* @param @param proStorageSn
	* @param @return  参数说明 
	* @return TransResult    返回类型
	* @author jzh 
	* @throws 
	*/
	@PostMapping("charge/list/out")
	public TransResult chargeListOut(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows, ProStorageSn proStorageSn) {
		proStorageSn.preQuery();
		Pager<ProStorageSn> result = proStorageSnService.findChargeOut(page, rows, proStorageSn);
		
		String sumInfo = result.getOrder();
		if (sumInfo != null && sumInfo.length() > 0) {
			result.setOrder(sumInfo);
		}
		
		return success(result);
	}
	
	/** 
	* @Title: editProStorageSnOut 
	* @Description: 记账出库修改
	* @param @param proStorageSn
	* @param @return  参数说明 
	* @return TransResult    返回类型
	* @author jzh 
	* @throws 
	*/
	@PostMapping("prosnout/edit")
	public TransResult editProStorageSnOut(ProStorageSn proStorageSn) {
		TransResult result = new TransResult();
		Date now = new Date();
		if(proStorageSn.getStorageSnId() == null || "".equals(proStorageSn.getStorageSnId())){
			proStorageSn.setActiveFlag("1");
			proStorageSn.setBarcodeStatus("0");
			proStorageSn.setCreateBy(getLoginName());
			proStorageSn.setGmtCreate(now);
			if(proStorageSn.getAmount() != null){
				proStorageSn.setAmount(proStorageSn.getAmount().negate());
			}else{
				result.setCode(Constant.FAIL);
				result.setMsg("请输入出库数量！");
				return result;
			}
			Resp resp = proStorageSnService.createChargeOut(proStorageSn);
			result.setCode(resp.getCode());
			result.setMsg(resp.getMsg());
			return result;
		}else{
			proStorageSn.setLastModifiedBy(getLoginName());
			proStorageSn.setGmtModified(now);
			if(proStorageSn.getAmount() != null){
				proStorageSn.setAmount(proStorageSn.getAmount().negate());
			}
			Resp resp = proStorageSnService.updateChargeOut(proStorageSn);
			result.setCode(resp.getCode());
			result.setMsg(resp.getMsg());
			return result;
		}
	}
	
	/** 
	* @Title: contactProUpdate 
	* @Description: 批量修改成品合同号
	* @param @param proStorageSn
	* @param @return  参数说明 
	* @return TransResult    返回类型
	* @author jzh 
	* @throws 
	*/
	@PostMapping("procontact/update")
	public TransResult contactProUpdate(ProStorageSn proStorageSn){
		TransResult result = new TransResult();
		String LoginName = getLoginName();
		proStorageSn.setLastModifiedBy(LoginName);
		result.setCode(Constant.SUCCESS);
		if(proStorageSn.getContractNoOld().equals(proStorageSn.getContractNo())){
			result.setCode(Constant.FAIL);
			result.setMsg("修改合同号与原合同号相同，请更换！");
			return result;
		}
		try{
			Resp resp = proStorageSnService.batchUpdateProContact(proStorageSn);
			if(resp != null){
				result.setCode(resp.getCode());
				result.setMsg(resp.getMsg());
			}
		}catch(RuntimeException e){
			result.setCode(Constant.FAIL);
			result.setMsg(e.getMessage());
		}
		
		return result;
	}
	
	/** 
	* @Title: contractProductRequirement 
	* @Description: 成品合同销售报表
	* @param @param proStorageSn
	* @param @return  参数说明 
	* @return TransResult    返回类型
	* @author jzh 
	* @throws 
	*/
	@PostMapping("contractProduct/requirement")
	public TransResult contractProductRequirement(@RequestBody ProStorageSn proStorageSn) {
		TransResult result = new TransResult();
		//
		if(proStorageSn.getContractNo()==null || proStorageSn.getContractNo().equals("")){
			result.setCode(Constant.FAIL);
			result.setMsg("请输入合同号");
			return result;
		}
		
		MesConProRequired mesConProRequired = new MesConProRequired();
		mesConProRequired.setSalesCode(proStorageSn.getContractNo());
		
		String url =  mesProperties.getUrl() + "/imes-provider/external/interfaces/contract/product";
		JSONObject handResp = mesInterfaceService.publicWSJson(url, MediaType.APPLICATION_JSON_TYPE, JSON.toJSONString(mesConProRequired));
		JSONArray listjson = handResp.getJSONObject("data").getJSONArray("list");
		
		ConProCondDto conProCondDto = new ConProCondDto();
		conProCondDto.setContractNo(proStorageSn.getContractNo());
		List<MesConProRequired> list = proStorageSnService.findConProRequired(conProCondDto);
		
		List<MesConProRequired> mesList = new ArrayList<MesConProRequired>();
		if(list.size()>0){
			for(int i=0; i<list.size();i++){
				MesConProRequired conProRequired = new MesConProRequired();
				conProRequired.setContractNo(list.get(i).getContractNo());
				conProRequired.setModel(list.get(i).getModel());
				conProRequired.setInAmount(list.get(i).getInAmount());
				conProRequired.setOutAmount(list.get(i).getOutAmount());
				conProRequired.setKcAmount(list.get(i).getKcAmount());
				conProRequired.setJcAmount(list.get(i).getJcAmount());
				conProRequired.setJrAmount(list.get(i).getJrAmount());
				conProRequired.setUnit(list.get(i).getUnit());
				
				for(int j=0; j<listjson.size();j++){
					JSONObject temp = listjson.getJSONObject(j);
					if(list.get(i).getModel().equals(temp.getString("modelCode"))){
						conProRequired.setDemand(new BigDecimal (temp.getString("demand")));
//						conProRequired.setUnit(temp.getString("measureUnit"));
//						conProRequired.setOwner(temp.getString("owner"));
						break;
					}
				}
				
				mesList.add(conProRequired);
			}
		}
	
		return success(mesList);
	}
}
